<template>
  <div v-loading="loading">
   <container-info-view :data="data" @getData="getData"></container-info-view>

    <footer-nav>
      <del-container-btn :data="data" @delRow="goBack"></del-container-btn>
      <el-button  @click="goBack">{{$t('common.back')}}</el-button>
      <el-button type="primary" @click="finishBox" :disabled="boxIsEveryInstall" v-if="data.status === 'wait_make_cabinet' && isFirstLegRole()">确认已装柜</el-button>
      <change-container-status-btn :data="data" @changeRow="getData"></change-container-status-btn>
      <el-button type="primary" @click="finishSorting" v-if="data.status === 'wait_sorting' && isInboundSortingRole()" :loading="finishLoading">确认已分拣</el-button>
    </footer-nav>
  </div>
</template>

<script>
import {
  boxChangeContainer,
  changeStatus, containerBoxAllInstall, containerBoxAllSorted,
  editContainerBox, finishedSorting,
  getContainerInfo,
  installBox,
  removeContainerBox
} from "@/api/container";
import {getShipmentTypeStr2} from "@/utils/shipment";
import FooterNav from "@/components/Common/FooterNav.vue";
import DelContainerBtn from "@/views/container/components/DelContainerBtn.vue";
import ChangeContainerStatusBtn from "@/views/container/components/ChangeContainerStatusBtn.vue";
import ContainerSteps from "@/views/container/components/ContainerSteps.vue";
import ContainerInfoTable from "@/views/container/components/ContainerInfoTable.vue";
import {deepCopy} from "@/utils";
import {getTransferTypeName, isFirstLegRole, isInboundSortingRole} from "@/utils/common";
import ContainerInfoView from "@/views/container/components/containerInfoView.vue";
import {STATUS_SORTED} from "@/utils/boxLabel";

export default {
  name: 'containerInfo',
  components: {ContainerInfoView, ChangeContainerStatusBtn, DelContainerBtn, FooterNav},
  data(){
    return {
      id: '',
      loading: false,
      data: {},
      boxTable: [],
      removeLoading: false,
      editDialog: false,
      dialogForm: {
        type: 'add',
        boxIds: '',
      },
      digBtnLoading: false,
      notFoundBox: [],
      otherBox: [], // 其他货件的箱唛
      diffTypeBox: [], // 不同运输类型的箱唛
      installed: [], // 已经装柜了 不可再操作
      editFailDialog: false,
      history: [],
      finishLoading: false,
      logistics: null,
      logisticsLimit: true,
    }
  },
  computed: {
    boxIsEveryInstall(){
      return !this.boxTable.every(item=> item.isInstall)
    },
    logisticsDetail(){
      if(!this.logistics){
        return []
      }
      const arr = deepCopy(this.logistics.allDetail)
      if(!this.logisticsLimit){
        return arr
      }
      return arr.splice(0, 5)
    },
    isAir(){
      return this.data.transferType === 'air_fast' || this.data.transferType === 'air_slow';
    }
  },
  created() {
    this.id = this.$route.query.id
    if(!this.id){
      this.$errorMessage('缺少参数');
      return;
    }
    this.getData()
  },
  methods: {
    isInboundSortingRole,
    isFirstLegRole,
    getTransferTypeName,
    getShipmentTypeStr2,
    getData(){
      this.loading = true
      getContainerInfo(this.id)
        .then(res=>{
          this.loading = false
          if(res.error === 0){
            this.data = res.data
            this.history = this.data.history
            this.boxTable = res.data.boxList
            this.logistics = res.data.logistics
          }else{
            this.$errorMessage(res.message)
          }
        })
    },
    removeBox(row){
      let title = '确认移除？'
      let message = '确认将该货件移出当前货柜吗，移除后其他货柜可以再次添加该货件';
      this.$confirm(message,title)
        .then(()=>{
          this.removeLoading = true
          const data = {
            id: this.data.id,
            boxId: row.boxId,
          }

          removeContainerBox(data)
            .then(res=>{
              this.removeLoading = false
              if(res.error === 0){
                this.$successMessage(res.message)
                this.getData()
              }else{
                this.$errorMessage(res.message)
              }
            })
        })
        .catch(()=>{

        })
    },
    showEditDialog(){
      this.editDialog = true
      this.dialogForm.type = 'add'
      this.dialogForm.boxIds = ''
    },
    submitDialogForm(){
      const data = {
        id: this.data.id,
        type: this.dialogForm.type,
        boxIds: [],
      }
      data.boxIds = this.dialogForm.boxIds.split('\n')
      data.boxIds = data.boxIds.map(item=> item.trim()).filter(item=> item)
      if(!data.boxIds.length){
        this.$errorMessage('请输入箱唛')
        return
      }
      this.digBtnLoading = true
      this.notFoundBox = [];
      this.otherBox = [];
      this.diffTypeBox = [];
      editContainerBox(data)
        .then(res=>{
          this.digBtnLoading = false
          if(res.error === 0){
            this.notFoundBox = res.data.notFound || []
            this.otherBox = res.data.otherContainer || []
            this.diffTypeBox = res.data.transferTypeDiff || []
            this.installed = res.data.installed || []
            this.getData()
            if(this.notFoundBox.length > 0 || this.otherBox.length > 0 || this.diffTypeBox.length > 0 || this.installed.length > 0){
              this.editFailDialog = true
            }else{
              this.$successMessage(res.message)
            }
            this.editDialog = false
          }else{
            this.$errorMessage(res.message)
          }
        })
    },
    // 将其他货柜箱唛添加到当前货柜
    addOtherBox(){
      // 没有箱唛
      if(this.otherBox.length <= 0){
        return
      }
      const data = {
        id: this.data.id,
        boxIds: this.otherBox,
      }
      boxChangeContainer(data)
        .then(res=>{
          if(res.error === 0){
            this.editFailDialog = false
            this.getData()
            this.$successMessage(res.message)
          }else{
            this.$errorMessage(res.message)
          }
        })
    },
    goBack(){
      this.$router.go(-1)
    },
    installRow(row){
      row.isInstall = 1;
      installBox({
        id: this.data.id,
        boxId: row.boxId,
      })
        .then(res=>{

        })
    },
    finishBox(){
      changeStatus({
        id: this.data.id,
        status: 'wait_customs_declaration', // 待报关
      })
        .then(res=>{
          if(res.error === 0){
            this.getData()
            this.$successMessage(res.message)
          }else{
            this.$eMsg(res.message)
          }
        })
    },
    finishSorting(){
      new Promise((resolve, reject)=>{
        let title = '确认已分拣'
        let message = ''
        const flag = this.boxTable.every(item=>item.isSorting === 1)
        const set = new Set();
        this.boxTable.forEach(item=> {
          if(item.isSorting !== 1){
            set.add(item.boxId)
          }
        })
        const num = set.size
        if(!flag){
          message += `<div class="font-red">未分拣箱数：${num}</div>`
          message += '<div class="font-red">确认本单货件已扫描分拣完毕？“待分拣”状态的货件代表货件未收到/丢失，不会计入库存，后续也不能再操作上架</div>';
        }
        this.$confirm(message, title, {
          dangerouslyUseHTMLString: true,
        })
          .then(() => {
            resolve()
          }).catch(() => {
            reject()
          });
      })
        .then(()=>{
          this.finishLoading = true
          finishedSorting(this.data.id)
            .then(res=>{
              this.finishLoading = false
              if(res.error === 0){
                this.$successMessage(res.message)
                this.getData()
              }else{
                this.$errorMessage(res.message)
              }
            })
        })
    },
    jumpGF(){
      if(!this.logistics.website){
        return;
      }
      const url = this.logistics.website
      window.open(url, '_blank');
    },
    allInstall(){
      let title = '确认全部已装柜?'
      let html = `<div>确认当前货柜的所有货件已装柜完毕，变更为所有箱唛为已装柜状态？</div>`
      html += `<div class="font-red">确认后货柜状态将直接变更为“待报关”，无需再操作下方的「确认已装柜」按钮</div>`
      this.$confirm(html,title,{
        dangerouslyUseHTMLString: true,
      })
        .then(()=>{
          containerBoxAllInstall(this.data.id)
            .then(res=>{
              if(res.error === 0){
                this.$successMessage(res.message)
                this.getData()
              }else{
                this.$errorMessage(res.message)
              }
            })
        })
        .catch(()=>{})
    },
    allSorted(){
      let title = '确认全部已分拣？'
      let html = `<div>确认当前货件单的所有货件已分拣完毕，变更为所有箱唛为已分拣状态？</div>`
      html += `<div class="font-red">确认后货件单状态将直接变更为“已分拣”，无需再操作下方的「确认已分拣」按钮</div>`
      this.$confirm(html,title,{
        dangerouslyUseHTMLString: true,
      })
        .then(()=>{
          containerBoxAllSorted(this.data.id)
            .then(res=>{
              if(res.error === 0){
                this.$successMessage(res.message)
                this.getData()
              }else{
                this.$errorMessage(res.message)
              }
            })
        })
        .catch(()=>{})
    }
  }
}
</script>

<style scoped lang="scss">
.wrap{
  padding: 10px 30px 80px;
  .content{
    .header-card{
      position: relative;
      font-size: 14px;
      background-color: rgba(242, 242, 242, 1);
      p{
        margin: 10px 0;
        padding: 0;
      }
      .font-bold{
        font-weight: bold;
      }
      .button{
        position: absolute;
        display: flex;
        flex-direction: column;
        right: 20px;
        top: 30px;
      }
    }
    .detail{
      margin-top: 20px;
      .table-header{
        display: flex;
        align-items: center;
        justify-content: space-between;
        margin-bottom: 10px;
        .left{
          .table-title{
            font-size: 18px;
            font-weight: 500;
          }
        }

      }
      .logistics-box{
        padding: 20px 30px 0;
        border: 1px solid #cccccc;
        border-radius: 5px;
        .logistics-item{
          margin-bottom: 20px;
          font-size: 15px;
          font-weight: 350;
          .time{
            color: #AAAAAA;
          }
        }
        position: relative;
        .gf-btn{
          position: absolute;
          right: 20px;
          top: 20px;
        }
        .show-limit{
          position: absolute;
          right: 20px;
          bottom: 10px;
        }
      }
    }
  }
  .season-title{
    font-size: 18px;
    font-weight: 500;
  }
}

</style>
